Param($SrcPath, $DstPattern)

$all_start = Get-Date

$global:n_episodes = 0
$global:n_proofs = 0
$global:n_samples = 0
$global:n_subs = 0

Write-Output "Looking tv releases in '$SrcPath'..."

function CreateTvReleaseAdditionalFiles([string] $work_path, [string] $dst_path, 
                                        [string] $ident_string, [string] $item_name,
                                        [ref] $item_counter) {
    $item_path = Join-Path $work_path $item_name
    if (Test-Path $item_path) {
        $items = Get-ChildItem $item_path | where {! $_.PSIsContainer}
        $items_found = $false
        ForEach ($item in $items) {
            if ($item -match ("(.*\.)" + $ident_string)) {
                $item_counter.value++
                $items_found = $true
                $src_fullname = Join-Path $item_path ($matches[1] + $ident_string + "*")
                $dst_fullname = Join-Path $dst_path $item_name
                if (!(Test-Path "$dst_fullname")) {
                    New-Item "$dst_fullname" -itemType directory | Out-Null
                }
                # Write-Host "Trying to move $src_fullname --> $dst_fullname..."
                Move-Item "$src_fullname" "$dst_fullname"
            }
        }
        if ($items_found) {
            Write-Host " + $item_name" -nonewline
        }
    }
}
function RemoveEmptyTvReleasePath([string] $work_path, [string] $item_name) {
    $item_path = Join-Path $work_path $item_name
    if (Test-Path $item_path) {
        if (!(Test-Path (Join-Path $item_path "*"))) {
            Write-Host "Removing $item_name dir since it's now empty."
            Remove-Item $item_path
        }
        else {
            Write-Host "Leaving $item_name dir since it contains stuff."
        }
    }
    else {
        Write-Host "No $item_name dir found."
    }
}

function CreateTvReleaseStructure([string] $WorkPath) {
    $items = Get-ChildItem $WorkPath | where {! $_.PSIsContainer}
    ForEach ($item in $items) {
#        if ($item -match "(\d{2}[a-z]?_|s\d{2}e\d{2}_|)(.*?)(_SUBMUX|_se|_fixed|_CD.|_\d|)\.(avi|mkv|mp4)$") {
        if ($item -match "(.*)\.s(\d{2})e(\d{2}).*\.rar$") {
            $tvrel_pre = $matches[1]
            $tvrel_season = $matches[2]
            $tvrel_episode = $matches[3]
            $tvrel_sestring = "S" + $tvrel_season + "E" + $tvrel_episode
            $tvrel_src_name = $tvrel_pre + "." + $tvrel_sestring + "*"
            $tvrel_dst_name = $DstPattern -replace "%s", $tvrel_sestring
            $tvrel_src_fullname = Join-Path $WorkPath $tvrel_src_name
            $tvrel_dst_fullname_final = Join-Path $WorkPath $tvrel_dst_name
            $tvrel_dst_fullname = Join-Path $WorkPath ("___" + $tvrel_dst_name)
            if (!(Test-Path $tvrel_dst_fullname)) {
                Write-Host "Creating " -nonewline; Write-Host "$tvrel_dst_fullname" -f green -nonewline
                $global:n_episodes++
                New-Item "$tvrel_dst_fullname" -itemType directory | Out-Null
                # Write-Host "Trying to move $tvrel_src_fullname --> $tvrel_dst_fullname..."
                Move-Item "$tvrel_src_fullname" "$tvrel_dst_fullname"
                # Try to find matching additional files
                CreateTvReleaseAdditionalFiles $WorkPath $tvrel_dst_fullname $tvrel_sestring "Proof" ([ref]$global:n_proofs)
                CreateTvReleaseAdditionalFiles $WorkPath $tvrel_dst_fullname $tvrel_sestring "Sample" ([ref]$global:n_samples)
                CreateTvReleaseAdditionalFiles $WorkPath $tvrel_dst_fullname $tvrel_sestring "Subs" ([ref]$global:n_subs)
                Rename-Item "$tvrel_dst_fullname" "$tvrel_dst_name"
                Write-Host "."
            }
            else {
                Write-Host "Destination path '$tvrel_dst_fullname' exist beforehand, skipping."
            }
        }
    }
    RemoveEmptyTvReleasePath $WorkPath "Proof"
    RemoveEmptyTvReleasePath $WorkPath "Sample"
    RemoveEmptyTvReleasePath $WorkPath "Subs"
}

CreateTvReleaseStructure $SrcPath

function GetNow() {
    return Get-Date -format "yyyy-MM-dd HH:mm:ss"
}

$all_end = Get-Date
$total_time = New-Timespan $all_start $all_end
$now = GetNow
Write-Output "`n"
Write-Output "Finished at $now. Processing took $total_time."
Write-Output "Found $global:n_episodes episodes with $global:n_proofs proof files, $global:n_samples sample files and $global:n_subs sub files."
